package service

import (
	"sdc/repository/db/model"

	"gorm.io/gorm"
)

type CategoryService struct {
	db *gorm.DB
}

func NewCategoryService(db *gorm.DB) *CategoryService {
	return &CategoryService{db: db}
}

// CreateCategory 创建分类
func (s *CategoryService) CreateCategory(category *model.Category) error {
	// 检查分类名是否重复
	var count int64
	if err := s.db.Model(&model.Category{}).
		Where("name = ? AND status = 1", category.Name).
		Count(&count).Error; err != nil {
		return err
	}

	if count > 0 {
		return ErrCategoryNameExists
	}

	// 设置默认值
	if category.Status == 0 {
		category.Status = 1 // 默认启用
	}

	return s.db.Create(category).Error
}

// UpdateCategory 更新分类
func (s *CategoryService) UpdateCategory(category *model.Category) error {
	// 检查分类是否存在
	var existingCategory model.Category
	if err := s.db.First(&existingCategory, category.ID).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return ErrCategoryNotFound
		}
		return err
	}

	// 检查名称是否重复（排除自身）
	var count int64
	if err := s.db.Model(&model.Category{}).
		Where("name = ? AND status = 1 AND id != ?", category.Name, category.ID).
		Count(&count).Error; err != nil {
		return err
	}

	if count > 0 {
		return ErrCategoryNameExists
	}

	// 更新分类
	return s.db.Model(category).Updates(map[string]interface{}{
		"name":   category.Name,
		"sort":   category.Sort,
		"status": category.Status,
	}).Error
}

// ListCategories 获取分类列表
func (s *CategoryService) ListCategories() ([]model.Category, error) {
	var categories []model.Category
	err := s.db.Where("status = ?", 1).
		Order("sort DESC, id ASC").
		Find(&categories).Error
	return categories, err
}

// CreateCategory 创建分类
func (s *AdminService) CreateCategory(category *model.Category) error {
	// 检查分类名是否重复
	var count int64
	s.db.Model(&model.Category{}).
		Where("name = ? AND status = 1", category.Name).
		Count(&count)
	if count > 0 {
		return ErrCategoryNameExists
	}

	return s.db.Create(category).Error
}

// UpdateCategory 更新分类
func (s *AdminService) UpdateCategory(category *model.Category) error {
	// 检查分类名是否重复（排除自身）
	var count int64
	s.db.Model(&model.Category{}).
		Where("name = ? AND status = 1 AND id != ?", category.Name, category.ID).
		Count(&count)
	if count > 0 {
		return ErrCategoryNameExists
	}

	return s.db.Model(category).
		Updates(map[string]interface{}{
			"name":   category.Name,
			"sort":   category.Sort,
			"status": category.Status,
		}).Error
}

// ListCategories 获取分类列表
func (s *AdminService) ListCategories() ([]model.Category, error) {
	var categories []model.Category
	err := s.db.Order("sort DESC, id ASC").Find(&categories).Error
	return categories, err
}

// DeleteCategory 删除分类
func (s *AdminService) DeleteCategory(id uint64) error {
	return s.db.Delete(&model.Category{}, id).Error
}
